<?php
App::uses('AppModel', 'Model');

class User extends AppModel {


	public $primaryKey = 'id_users';
	public $displayField = 'nome';

	public $validate = array(
		'id_users' => array(
			'numeric' => array(
				'rule' => array('numeric'),
			),
		),
		'username' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
		),
		'password' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
			'confirmacao'=>array(
				'rule'=>array('senhasIguais')
			)
		),
		'nome' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
		),
		'empresas_id' => array(
			'notempty' => array(
				'rule' => array('notempty'),
			),
		),
		'senha_atual'=>array(
			'notempty' =>array(
				'rule'=>array('notempty')
			),
		),
		'senha_confirmacao'=>array(
			'notempty'=>array(
				'rule'=>array('notempty')
			)
		),
		'email'=>array(
			'email'=>array(
				'rule' => array('email')
			)
		)
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'Empresa' => array(
			'className' => 'Empresa',
			'foreignKey' => 'empresas_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
	
		public $hasAndBelongsToMany = array(
		'Projeto' => array(
			'className' => 'Projeto',
			'joinTable' => 'projetos_users',
			'foreignKey' => 'users_id',
			'associationForeignKey' => 'projetos_id',
			'unique' => true,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'finderQuery' => '',
			'deleteQuery' => '',
			'insertQuery' => ''
		)
	);
	
	public $hasMany = array(
		'NaoLidas'=>array(
			'className'=>'NaoLido',
			'foreignKey'=>'users_id'
		)
	);
	
	function beforeSave($options = array()) {
		if(isset($this->data['User']['password']))
        	 $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        return true;
    }
    
    public function senhasIguais($data){
    	if($data['password'] == $this->data['User']['senha_confirmacao'])
    		return true;
    	$this->invalidate('senha_confirmacao', 'As senhas são diferentes');
    	return false;
    }
    
    public function senhaCorreta($id, $senha){
    	$usuario = $this->read('password', $id);
    	if($usuario['User']['password'] == AuthComponent::password($senha))
    		return true;
    	else {
    		$this->invalidate('senha_atual', 'Digite a senha correta');
    		return false;
    	}
    }
    
    public function numero_nao_lidas($id){
    	return $this->NaoLidas->numero_nao_lidas($id);
    }
}
